package com.nbcio.modules.erp.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nbcio.modules.erp.base.constant.CommonConst;
import com.nbcio.modules.erp.base.entity.ErpCustomer;
import com.nbcio.modules.erp.base.entity.ErpCustomerLink;
import com.nbcio.modules.erp.base.mapper.ErpCustomerLinkMapper;
import com.nbcio.modules.erp.base.mapper.ErpCustomerMapper;
import com.nbcio.modules.erp.base.service.IErpCustomerService;
import com.nbcio.modules.erp.cart.entity.SysUser;
import com.nbcio.modules.erp.cart.service.ISysUserServiceNew;
import com.nbcio.modules.flowable.apithird.business.entity.FlowMyBusiness;
import com.nbcio.modules.flowable.apithird.service.FlowCallBackServiceI;
import com.nbcio.modules.flowable.apithird.service.FlowCommonService;
import com.nbcio.modules.flowable.utils.StatusEnum;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @Description: erp_customer
 * @Author: nbacheng
 * @Date:   2024-04-16
 * @Version: V1.0
 */
@Service("erpCustomerService")
public class ErpCustomerServiceImpl extends ServiceImpl<ErpCustomerMapper, ErpCustomer> implements IErpCustomerService , FlowCallBackServiceI{



    @Autowired
    FlowCommonService flowCommonService;
	@Autowired
	private ErpCustomerMapper erpCustomerMapper;
	@Autowired
	private ErpCustomerLinkMapper erpCustomerLinkMapper;

	@Autowired
	private ISysUserServiceNew sysUserService;


	@Override
	@Transactional
	public void saveMain(ErpCustomer erpCustomer, List<ErpCustomerLink> erpCustomerLinkList) {

		try {
			erpCustomerMapper.insert(erpCustomer);
			if (erpCustomerLinkList != null && erpCustomerLinkList.size() > 0) {
				for (ErpCustomerLink entity : erpCustomerLinkList) {
					//外键设置
					entity.setIdH(erpCustomer.getId());
					erpCustomerLinkMapper.insert(entity);
				}
			}

			LambdaQueryWrapper<ErpCustomer> query = new LambdaQueryWrapper<>();
			query.eq(ErpCustomer::getPhone, erpCustomer.getPhone())
					.ne(ErpCustomer::getId, erpCustomer.getId());
			ErpCustomer one = getOne(query);
			if (one != null){
				throw new RuntimeException("已经存在手机号为："+erpCustomer.getPhone()+"的客户！");
			}

			LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
			wrapper.eq(SysUser::getPhone, erpCustomer.getPhone());
			SysUser user = sysUserService.getOne(wrapper);
			if (user!=null){
				throw new RuntimeException("已经存在手机号为："+erpCustomer.getPhone()+"的用户！");
			}


			//同步用户
			String username = erpCustomer.getCode();
			String password = CommonConst.DEFAULT_PASSWORD;
			String phone = erpCustomer.getPhone();
			String name = erpCustomer.getName();

			SysUser sysUser = new SysUser();
			sysUser.setUsername(username);
			String salt = oConvertUtils.randomGen(8);
			sysUser.setSalt(salt);
			String passwordEncode = PasswordUtil.encrypt(username, password, salt);
			sysUser.setPassword(passwordEncode);
			sysUser.setRealname(name);
			sysUser.setWorkNo(phone);
			sysUser.setPhone(phone);
			sysUser.setStatus(1);
			sysUser.setDelFlag(0);
			sysUser.setUserIdentity(1);
			sysUser.setActivitiSync(1);

			sysUserService.save(sysUser);

		}catch (Exception e){
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	@Transactional
	public void updateMain(ErpCustomer erpCustomer,List<ErpCustomerLink> erpCustomerLinkList) {

		erpCustomerMapper.updateById(erpCustomer);

		//1.先删除子表数据
		erpCustomerLinkMapper.deleteByMainId(erpCustomer.getId());

		//2.子表数据重新插入
		if(erpCustomerLinkList!=null && erpCustomerLinkList.size()>0) {
			for(ErpCustomerLink entity:erpCustomerLinkList) {
				//外键设置
				entity.setIdH(erpCustomer.getId());
				erpCustomerLinkMapper.insert(entity);
			}
		}


		String code = erpCustomer.getCode();
		LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(SysUser::getUsername, code);
		SysUser user = sysUserService.getOne(wrapper);

		if (user!=null){
			if (!user.getPhone().equals(erpCustomer.getPhone())){
				user.setPhone(erpCustomer.getPhone());
				sysUserService.updateById(user);
			}
		}

	}

	@Override
	@Transactional
	public void delMain(String id) {
		erpCustomerLinkMapper.deleteByMainId(id);
		erpCustomerMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			erpCustomerLinkMapper.deleteByMainId(id.toString());
			erpCustomerMapper.deleteById(id);
		}
	}
    @Override
    public boolean removeById(Serializable id) {
        /**删除数据，移除流程关联信息**/
        flowCommonService.delActBusiness(id.toString());
        return super.removeById(id);
    }
    /**
     * 流程处理完成后的回调
     * @param business 里面包含流程运行的现状信息，业务层可根据其信息判断，书写增强业务逻辑的代码，<br/>
     *                 1、比如将其中关键信息存入业务表，即可单表业务操作,否则需要关联flow_my_business表获取流程信息<br/>
     *                 2、比如在流程进行到某个节点时(business.taskId)，需要特别进行某些业务逻辑操作等等<br/>
     */
      @Override
      public void afterFlowHandle(FlowMyBusiness business) {

           business.getTaskNameId();//接下来审批的节点
           business.getValues();//前端传进来的参数
           business.getActStatus();//流程状态 ActStatus.java
           //....其他
           ErpCustomer   erpCustomer= this.getById(business.getDataId());
//           erpCustomer.setActstatus(StatusEnum.getEnumKey(business.getActStatus()));
           // erpCustomer.
             this.updateById(erpCustomer);
        }


   /**
     * 根据业务id返回业务表单数据<br/>
     * @param dataId
     * @return
     */
        @Override
        public Object getBusinessDataById(String dataId) {
            return this.getById(dataId);
        }
    /**
     * 返回当前节点的流程变量
     * @param taskNameId 节点定义id
     * @param values 前端传入的变量，里面包含dataId
     * @return
     */
        @Override
        public Map<String, Object> flowValuesOfTask(String taskNameId, Map<String, Object> values) {
            return null;
        }
    /**
     * 返回当前节点的候选人username
     * @param taskNameId 节点定义id
     * @param values 前端传入的变量，里面包含dataId
     * @return
     */
        @Override
        public List<String> flowCandidateUsernamesOfTask(String taskNameId, Map<String, Object> values) {
            // 通过当前节点来判断下一个节点的候选人并写回到反参中，如果为null，流程模块会根据默认设置处理

            return null;
        }


        @Override
        public void relationAct(String dataId) {
             //flowCommonService.initActBusiness("实验授课申请：dataId"+dataId,dataId,"erpCustomerService","process_tpho5a4q","process_tpho5a4q:4:32128f7c-ce77-11ec-843e-927841cf098b");
        }

}
